const express = require('express')
const { WorkOrder, Material } = require('../models')
const router = express.Router()

// 获取生产排产列表
router.get('/schedule', async (req, res) => {
  try {
    const { page = 1, limit = 10, date } = req.query
    
    const where = {}
    if (date) {
      where.createdAt = {
        [Op.gte]: new Date(date),
        [Op.lt]: new Date(new Date(date).getTime() + 24 * 60 * 60 * 1000)
      }
    }
    
    const schedules = await WorkOrder.findAndCountAll({
      where,
      include: [
        { model: Material, as: 'product', attributes: ['name', 'code'] }
      ],
      order: [['priority', 'DESC'], ['createdAt', 'ASC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    })
    
    res.json({
      data: schedules.rows,
      pagination: {
        total: schedules.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    })
  } catch (error) {
    console.error('获取排产列表错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取现场看板数据
router.get('/kanban', async (req, res) => {
  try {
    const { workshop } = req.query
    
    // 获取今日生产数据
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    const todayWorkOrders = await WorkOrder.findAll({
      where: {
        createdAt: {
          [Op.gte]: today
        }
      },
      include: [
        { model: Material, as: 'product', attributes: ['name', 'code'] }
      ]
    })
    
    // 计算今日产量
    const todayProduction = todayWorkOrders.reduce((sum, order) => {
      return sum + parseFloat(order.actualQuantity || 0)
    }, 0)
    
    // 获取进行中的工单
    const runningOrders = await WorkOrder.findAll({
      where: { status: 'running' },
      include: [
        { model: Material, as: 'product', attributes: ['name', 'code'] }
      ],
      order: [['startTime', 'DESC']]
    })
    
    // 获取待生产工单
    const pendingOrders = await WorkOrder.findAll({
      where: { status: 'pending' },
      include: [
        { model: Material, as: 'product', attributes: ['name', 'code'] }
      ],
      order: [['priority', 'DESC'], ['createdAt', 'ASC']],
      limit: 10
    })
    
    res.json({
      data: {
        todayProduction,
        runningOrders: runningOrders.length,
        pendingOrders: pendingOrders.length,
        completedOrders: todayWorkOrders.filter(o => o.status === 'completed').length,
        runningOrdersList: runningOrders,
        pendingOrdersList: pendingOrders
      }
    })
  } catch (error) {
    console.error('获取看板数据错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取物料需求列表
router.get('/material', async (req, res) => {
  try {
    const { page = 1, limit = 10, status } = req.query
    
    // 这里简化处理，实际应该根据BOM和工单计算物料需求
    const materials = await Material.findAll({
      where: {
        currentStock: {
          [Op.lt]: sequelize.col('safeStock')
        }
      },
      order: [['currentStock', 'ASC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    })
    
    const total = await Material.count({
      where: {
        currentStock: {
          [Op.lt]: sequelize.col('safeStock')
        }
      }
    })
    
    res.json({
      data: materials,
      pagination: {
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    })
  } catch (error) {
    console.error('获取物料需求错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 创建物料需求
router.post('/material', async (req, res) => {
  try {
    const { materialId, quantity, priority } = req.body
    
    // 这里简化处理，实际应该创建物料需求单
    const material = await Material.findByPk(materialId)
    
    if (!material) {
      return res.status(404).json({ message: '物料不存在' })
    }
    
    // 可以创建采购申请等后续操作
    
    res.json({ message: '物料需求创建成功' })
  } catch (error) {
    console.error('创建物料需求错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

module.exports = router
